<template>
  <div>
    <el-form v-if="state == 'add' || state == 'edit'" class="addPaymentMange">
      <div style="display: flex; justify-content: space-between">
        <div>新增付款</div>
        <closeTagButton id="closeTagButtonRef" />
      </div>
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <div style="display: flex; justify-content: space-between">
            <div class="card-header">
              <div
                style="
                  width: 4px;
                  height: 20px;
                  background-color: #409eff;
                  margin-right: 5px;
                "
              />
              <span>合同信息</span>
            </div>
            <div>
              <!-- <el-button
              v-if="state == 'save' || state == 'edit'"
              type="primary"
              color="#1E3485"
              >保存</el-button
            > -->
            </div>
          </div>
        </template>
        <el-form :model="form" label-width="150px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="采购合同" style="width: 100%">
                <div class="flex w-full">
                  <el-select
                    v-model="form.contractName"
                    placeholder="请选择 采购合同"
                    clearable
                    :disabled="state == 'edit'"
                    @click="showSalescontract"
                    @clear="clear()"
                  />
                  <el-button
                    v-if="form.contractName"
                    class="ml-1"
                    @click="$message('跳转合同路径')"
                    >合同详情</el-button
                  >
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同编号" style="width: 100%">
                <el-input
                  v-model="form.contractNo"
                  placeholder=""
                  disabled
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="签订日期" style="width: 100%">
                <el-date-picker
                  v-model="form.signDate"
                  type="date"
                  placeholder=""
                  disabled
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目名称" style="width: 100%">
                <el-input
                  v-model="form.projectName"
                  placeholder=""
                  disabled
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同类型" style="width: 100%">
                <el-radio-group
                  v-model="form.contractMethod"
                  disabled
                  class="ml-4"
                >
                  <el-radio value="0">电线电缆及光纤光缆</el-radio>
                  <el-radio value="1">电梯及扶梯</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同总金额（元）" style="width: 100%">
                <el-input
                  v-model="form.contractTotalPrice"
                  placeholder=""
                  disabled
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <div style="display: flex; justify-content: space-between">
            <div class="card-header">
              <div
                style="
                  width: 4px;
                  height: 20px;
                  background-color: #409eff;
                  margin-right: 5px;
                "
              />
              <span>合同发票</span>
              <div style="margin-left: 10px">
                <!--                <el-button type="primary" color="#1E3485" @click="showinvoice"
                  >选择发票</el-button
                >-->
              </div>
            </div>
          </div>
        </template>
        <vxe-table
          border
          height="300"
          header-align="center"
          :data="invoiceTableData"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          size="mini"
          show-overflow
        >
          <vxe-column field="invoiceDate" title="开票日期" />
          <vxe-column field="invoicePrice" title="开票金额(元)" />
          <vxe-column field="invoiceNo" title="发票号码" />
          <vxe-column field="invoiceCode" title="发票代码" />
          <vxe-column field="receiveStatus" title="发票状态" />
          <vxe-column field="invoiceFile" title="发票附件">
            <template v-slot="{ row }">
              <div v-for="item in row.invoiceFile">{{ item.name }}</div>
            </template>
          </vxe-column>
          <vxe-column field="settlementFile" title="结算单附件">
            <template v-slot="{ row }">
              <div v-for="item in row.settlementFile">{{ item.name }}</div>
            </template>
          </vxe-column>
          <vxe-colgroup title="付款信息" fixed="right">
            <vxe-column field="contractPrePrice" title="合同预付款(元)" />
            <vxe-column field="orderPrePrice" title="订单预付款(元)" />
            <vxe-column field="prePrice" title="本次付款金额(元)" />
            <vxe-column field="receivePrice" title="应收已付款(元)" />
            <vxe-column field="noReceivePrice" title="应收未付款(元)" />
          </vxe-colgroup>
          <vxe-colgroup title="收款信息" fixed="right">
            <vxe-column field="paymentInvoicePrice" title="发票金额(元)" />
            <vxe-column field="paymentPrice" title="应付已收款(元)" />
            <vxe-column field="noPaymentPrice" title="应付未收款(元)" />
          </vxe-colgroup>
          <vxe-column title="操作" fixed="right" width="100">
            <!-- 操作列按钮 -->
            <template v-slot="{ row }">
              <vxe-button mode="text">删除</vxe-button>
              <vxe-button
                mode="text"
                @click="toDetail({ id: row.id, action: 'view' }, 'view')"
                >查看
              </vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
      </el-card>
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <div style="display: flex; justify-content: space-between">
            <div class="card-header">
              <div
                style="
                  width: 4px;
                  height: 20px;
                  background-color: #409eff;
                  margin-right: 5px;
                "
              />
              <span>合同付款记录</span>
            </div>
          </div>
        </template>
        <vxe-table
          border
          height="300"
          header-align="center"
          :data="CollectionTableData"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          size="mini"
          show-overflow
        >
          <vxe-column field="receiveDate" title="付款时间" />
          <vxe-column field="receiveType" title="付款方式" />
          <vxe-column field="invoiceNo" title="发票号" width="200" />
          <vxe-column field="receivePrice" title="付款金额(元)" />
          <vxe-column field="contractPrePrice" title="含合同预付款(元)" />
          <vxe-column field="orderPrePrice" title="含订单预付款(元)" />
          <vxe-column field="file" title="附件" />
          <vxe-column field="mark" title="内容及用途" />
        </vxe-table>
      </el-card>
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <div style="display: flex; justify-content: space-between">
            <div class="card-header">
              <div
                style="
                  width: 4px;
                  height: 20px;
                  background-color: #409eff;
                  margin-right: 5px;
                "
              />
              <span>付款认领</span>
            </div>
            <div>
              <el-button
                v-if="state == 'add' || state == 'edit'"
                type="primary"
                color="#1E3485"
                @click="rules(ruleFormRef)"
                >保存</el-button
              >
            </div>
          </div>
        </template>
        <el-form
          ref="ruleFormRef"
          :model="form"
          label-width="150px"
          :rules="rulesForStepOne"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="关联收款" style="width: 100%">
                <div>
                  <vxe-table
                    border
                    max-height="300"
                    header-align="center"
                    :data="SKTableData"
                    :column-config="{ resizable: true }"
                    :row-config="{ isHover: true }"
                    size="mini"
                    show-overflow
                  >
                    <vxe-column
                      field="relatedReceiveDate"
                      title="收款时间"
                      width="180"
                    />
                    <vxe-column
                      field="relatedReceiveType"
                      title="收款方式"
                      width="180"
                    />
                    <vxe-column
                      field="relatedReceiveAmount"
                      title="收款金额"
                      width="180"
                    />
                    <vxe-column
                      title="操作"
                      fixed="right"
                      width="100"
                      align="center"
                    >
                      <!-- 操作列按钮 -->
                      <template v-slot="{}">
                        <vxe-button
                          mode="text"
                          status="primary"
                          @click="showCollection"
                          >关联收款</vxe-button
                        >
                      </template>
                    </vxe-column>
                  </vxe-table>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item
                label="付款时间"
                prop="receiveDate"
                style="width: 100%"
              >
                <el-date-picker
                  v-model="form.receiveDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择 付款时间"
                  @change="changeReceiveDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="付款金额"
                prop="receivePrice"
                style="width: 100%"
              >
                <el-input
                  v-model="form.receivePrice"
                  placeholder="请输入 付款金额"
                  clearable
                  @blur="receivePricechange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="付款方式"
                prop="receiveType"
                style="width: 100%"
              >
                <el-select
                  v-model="form.receiveType"
                  placeholder="请选择 付款方式"
                  clearable
                >
                  <el-option
                    v-for="item in OptionsFKFS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16">
              <el-form-item
                label="付款节点"
                prop="receiveNodeId"
                style="width: 100%"
              >
                <el-select
                  v-model="form.receiveNodeId"
                  placeholder="请选择 付款节点"
                  multiple
                  clearable
                  @change="changeReceiveNodeId"
                >
                  <el-option
                    v-for="item in OptionsFKJD"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="" style="width: 100%">
                <vxe-table
                  border
                  max-height="300"
                  header-align="center"
                  :data="receiveTableData"
                  :column-config="{ resizable: true }"
                  :row-config="{ isHover: true }"
                  size="mini"
                  show-overflow
                >
                  <vxe-column field="nodeName" title="付款节点" width="600" />
                  <vxe-column
                    field="backPaymentDate"
                    title="回款完成时间"
                    width="180"
                  />
                  <vxe-column
                    field="receiveDate"
                    title="付款时间"
                    width="180"
                  />
                  <vxe-column field="receivePrice" title="收款金额" width="200">
                    <template v-slot:default="{ row }">
                      <el-input
                        v-model="row.receivePrice"
                        @blur="updatereceivePrice"
                      />
                    </template>
                  </vxe-column>
                  <vxe-column
                    field="receiveStatus"
                    title="完成状态"
                    width="180"
                  >
                    <template v-slot:default="{ row }">
                      <el-checkbox
                        v-model="row.receiveStatus"
                        true-value="1"
                        false-value="0"
                        >收款完成</el-checkbox
                      >
                    </template>
                  </vxe-column>
                  <vxe-column field="" title="操作" width="100" fixed="right">
                    <template v-slot:default="{ row, index }">
                      <vxe-button
                        status="primary"
                        type="text"
                        size="small"
                        @click="delreceiveTableData(row, index)"
                        >取消</vxe-button
                      >
                    </template>
                  </vxe-column>
                </vxe-table>
              </el-form-item></el-col
            >
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="附件" style="width: 100%"
                ><el-upload
                  v-model:file-list="form.Files"
                  class="upload-demo"
                  :action="uploadUrl"
                  :headers="headers"
                  multiple
                  :on-preview="handlePreview"
                  :on-success="handleSuccess"
                  :before-remove="beforeRemove"
                  :limit="3"
                >
                  <el-button type="primary" color="#1E3485">
                    点击上传</el-button
                  >
                  <template #tip>
                    <div class="el-upload__tip">文件大小不能超过10M</div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="内容及用途" style="width: 100%">
                <el-input
                  v-model="form.mark"
                  :rows="1"
                  type="textarea"
                  placeholder="请输入 内容及用途"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </el-form>
    <el-tabs v-if="state == 'view'" v-model="activeName" type="card">
      <el-tab-pane label="付款详情" name="A">
        <el-form v-if="state == 'view'" class="viewPaymentMange">
          <el-card shadow="never" style="margin-top: 1%">
            <template #header>
              <div style="display: flex; justify-content: space-between">
                <div class="card-header">
                  <div
                    style="
                      width: 4px;
                      height: 20px;
                      background-color: #409eff;
                      margin-right: 5px;
                    "
                  />
                  <span>合同信息</span>
                </div>
                <div style="display: flex; justify-content: space-between">
                  <div />
                  <closeTagButton id="closeTagButtonRef" />
                </div>
              </div>
            </template>
            <el-form :model="form" label-width="150px">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="采购合同" style="width: 100%">
                    <el-select
                      v-model="form.contractName"
                      placeholder="请选择 采购合同"
                      clearable
                      disabled
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="合同编号" style="width: 90%">
                    <el-input
                      v-model="form.contractNo"
                      placeholder=""
                      disabled
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="签订日期" style="width: 90%">
                    <el-date-picker
                      v-model="form.signDate"
                      type="date"
                      placeholder=""
                      disabled
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目名称" style="width: 90%">
                    <el-input
                      v-model="form.projectName"
                      placeholder=""
                      disabled
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="合同类型" style="width: 90%">
                    <el-radio-group
                      v-model="form.contractMethod"
                      disabled
                      class="ml-4"
                    >
                      <el-radio value="0">电线电缆及光纤光缆</el-radio>
                      <el-radio value="1">电梯及扶梯</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="合同总金额（元）" style="width: 90%">
                    <el-input
                      v-model="form.contractTotalPrice"
                      placeholder=""
                      disabled
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
          <el-card shadow="never" style="margin-top: 1%">
            <template #header>
              <div style="display: flex; justify-content: space-between">
                <div class="card-header">
                  <div
                    style="
                      width: 4px;
                      height: 20px;
                      background-color: #409eff;
                      margin-right: 5px;
                    "
                  />
                  <span>合同发票</span>
                </div>
              </div>
            </template>
            <vxe-table
              border
              max-height="300"
              header-align="center"
              :data="invoiceTableData"
              :column-config="{ resizable: true }"
              :row-config="{ isHover: true }"
              size="mini"
              show-overflow
              :span-method="mergeRowMethod"
            >
              <vxe-column field="invoiceDate" title="开票日期" />
              <vxe-column field="invoicePrice" title="开票金额(元)" />
              <vxe-column field="invoiceNo" title="发票号码" />
              <vxe-column field="invoiceCode" title="发票代码" />
              <vxe-column field="receiveStatus" title="发票状态" />
              <vxe-column field="invoiceFile" title="发票附件">
                <template v-slot="{ row }">
                  <div v-for="item in row.invoiceFile">{{ item.name }}</div>
                </template>
              </vxe-column>
              <vxe-column field="settlementFile" title="结算单附件">
                <template v-slot="{ row }">
                  <div v-for="item in row.settlementFile">{{ item.name }}</div>
                </template>
              </vxe-column>
              <vxe-colgroup title="付款信息" fixed="right">
                <vxe-column field="contractPrePrice" title="合同预付款(元)" />
                <vxe-column field="orderPrePrice" title="订单预付款(元)" />
                <vxe-column field="prePrice" title="本次付款金额(元)" />
                <vxe-column field="receivePrice" title="应收已付款(元)" />
                <vxe-column field="noReceivePrice" title="应收未付款(元)" />
              </vxe-colgroup>
              <vxe-colgroup title="收款信息" fixed="right">
                <vxe-column field="paymentInvoicePrice" title="发票金额(元)" />
                <vxe-column field="paymentPrice" title="应付已收款(元)" />
                <vxe-column field="noPaymentPrice" title="应付未收款(元)" />
              </vxe-colgroup>
              <vxe-column title="操作" fixed="right" width="100">
                <!-- 操作列按钮 -->
                <template v-slot="{ row }">
                  <vxe-button
                    mode="text"
                    @click="toDetail({ id: row.id, action: 'view' }, 'view')"
                    >查看
                  </vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
          </el-card>
          <el-card shadow="never" style="margin-top: 1%">
            <template #header>
              <div style="display: flex; justify-content: space-between">
                <div class="card-header">
                  <div
                    style="
                      width: 4px;
                      height: 20px;
                      background-color: #409eff;
                      margin-right: 5px;
                    "
                  />
                  <span>合同付款记录</span>
                </div>
              </div>
            </template>
            <vxe-table
              border
              max-height="300"
              header-align="center"
              :data="CollectionTableData"
              :column-config="{ resizable: true }"
              :row-config="{ isHover: true }"
              size="mini"
              show-overflow
            >
              <vxe-column field="receiveDate" title="付款时间" />
              <vxe-column
                field="receiveType"
                :formatter="['valOfKey', OptionsFKFS]"
                title="付款方式"
              />
              <vxe-column field="nodeType" title="付款类型">
                <template v-slot:default="{ row }">
                  {{
                    row.nodeType === "0"
                      ? "合同预收款"
                      : row.nodeType === "1"
                        ? "订单预收款"
                        : row.nodeType === "2"
                          ? "实收款"
                          : ""
                  }}
                </template>
              </vxe-column>
              <vxe-column field="invoiceNo" title="发票号" width="200" />
              <vxe-column field="receivePrice" title="付款金额(元)" />
              <vxe-column field="contractPrePrice" title="含合同预付款(元)" />
              <vxe-column field="orderPrePrice" title="含订单预付款(元)" />
              <vxe-column field="file" title="附件">
                <template v-slot:default="{ row }">
                  <div v-for="item in row.file">
                    {{ item.name }}
                  </div>
                </template>
              </vxe-column>
              <vxe-column field="mark" title="内容及用途" />
            </vxe-table>
          </el-card>
          <el-card shadow="never" style="margin-top: 1%">
            <template #header>
              <div style="display: flex; justify-content: space-between">
                <div class="card-header">
                  <div
                    style="
                      width: 4px;
                      height: 20px;
                      background-color: #409eff;
                      margin-right: 5px;
                    "
                  />
                  <span>付款认领</span>
                </div>
              </div>
            </template>
            <el-form :model="form" label-width="150px" :rules="rulesForStepOne">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="关联收款" style="width: 100%">
                    <div>
                      <vxe-table
                        border
                        max-height="300"
                        header-align="center"
                        :data="SKTableData"
                        :column-config="{ resizable: true }"
                        :row-config="{ isHover: true }"
                        size="mini"
                        show-overflow
                      >
                        <vxe-column
                          field="relatedReceiveDate"
                          title="收款时间"
                          width="180"
                        />
                        <vxe-column
                          field="relatedReceiveType"
                          :formatter="['valOfKey', OptionsFKFS]"
                          title="收款方式"
                          width="180"
                        />
                        <vxe-column
                          field="relatedReceiveAmount"
                          title="收款金额"
                          width="180"
                        />
                      </vxe-table>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="收款时间" style="width: 100%">
                    <el-date-picker
                      v-model="form.receiveDate"
                      type="date"
                      placeholder="请选择 收款时间"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="付款金额" style="width: 100%">
                    <el-input
                      v-model="form.receivePrice"
                      placeholder="请输入 付款金额"
                      disabled
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="付款方式" style="width: 100%">
                    <el-select
                      v-model="form.receiveType"
                      placeholder="请选择 付款方式"
                      disabled
                      clearable
                    >
                      <el-option
                        v-for="item in OptionsFKFS"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="16">
                  <el-form-item label="付款节点" style="width: 100%">
                    <el-select
                      v-model="form.receiveNodeId"
                      placeholder="请选择 付款节点"
                      disabled
                      multiple
                    >
                      <el-option
                        v-for="item in OptionsFKJD"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="" style="width: 100%">
                    <vxe-table
                      border
                      max-height="300"
                      header-align="center"
                      :data="receiveTableData"
                      :column-config="{ resizable: true }"
                      :row-config="{ isHover: true }"
                      size="mini"
                      show-overflow
                    >
                      <vxe-column
                        field="nodeName"
                        title="付款节点"
                        width="400"
                      />
                      <vxe-column
                        field="backPaymentDate"
                        title="回款完成时间"
                        width="120"
                      />
                      <vxe-column
                        field="receiveDate"
                        title="付款时间"
                        width="120"
                      />
                      <vxe-column
                        field="receivePrice"
                        title="付款金额"
                        width="120"
                      />
                      <vxe-column
                        field="receiveStatus"
                        title="完成状态"
                        width="120"
                      >
                        <template v-slot:default="{ row }">
                          {{ +row.receiveStatus ? "收款完成" : "收款未完成" }}
                        </template>
                      </vxe-column>
                    </vxe-table>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="附件" style="width: 100%"
                    ><el-upload
                      v-model:file-list="form.Files"
                      class="upload-demo"
                      action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                      multiple
                      :on-preview="handlePreview"
                      :on-success="handleSuccess"
                      :before-remove="beforeRemove"
                      :limit="3"
                    >
                      <!-- <el-button type="primary" color="#1E3485">
                            点击上传</el-button
                          > -->
                      <template #tip>
                        <!-- <div class="el-upload__tip">文件大小不能超过10M</div> -->
                      </template>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="内容及用途" style="width: 100%">
                    <el-input
                      v-model="form.mark"
                      :rows="1"
                      type="textarea"
                      placeholder=""
                      disabled
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="审批记录" name="B">
        <div>
          <el-card shadow="never" style="margin-top: 1%">
            <template #header>
              <div style="display: flex; justify-content: space-between">
                <div>审批记录</div>
                <closeTagButton id="closeTagButtonRef" /></div
            ></template>
            <div class="examine">
              <img src="@/assets/img/CollectionExamine.jpg" alt="" />
            </div>
            <vxe-table
              border
              header-align="center"
              :column-config="{ resizable: true }"
              :row-config="{ isHover: true }"
              :data="examineTableData"
              size="mini"
              style="margin-top: 1%"
              show-overflow
            >
              <vxe-column type="seq" width="60" title="序号" align="center" />
              <vxe-column
                v-for="column in examineTableColumns"
                :key="column.field"
                :field="column.field"
                :title="column.title"
                :min-width="column.width"
                align="center"
                show-overflow
              >
                <template v-slot:default="{ row }">
                  {{ row[column.field] }}
                </template>
              </vxe-column>
            </vxe-table>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>
    <selectprocureContract
      :visible="dialogVisiblesales"
      @close="closeSalescontract"
    />
    <selectinvoice
      :contractId="form.contractId"
      :visible="dialogVisibleinvoice"
      @close="closeinvoice"
    />
    <selectCollection
      :contractId="form.saleContractId"
      :OptionsFKFS="OptionsFKFS"
      :visible="dialogVisibleCollection"
      @close="closeCollection"
    />
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import closeTagButton from "@/components/closeTagButton.vue";
import { Search, Upload } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { VxeTableInstance, VxePagerEvents, VxeTablePropTypes } from "vxe-table";
import { headers, uploadUrl } from "@/api/utils";
import type {
  ComponentSize,
  FormInstance,
  FormRules,
  UploadFile
} from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { getAuditHistoryTaskList } from "@/api/ERP_public";
import { getDict } from "@/api/utils";
import {
  getpaymentinfo,
  getpaymentinvoice,
  getpaymenthistory,
  getpaymentnode,
  paymentSaveOrUpdate,
  getcontractnodepaylist,
  paymentgetReceiveInvoice
} from "@/api/ERP_PaymentMange";

import selectprocureContract from "../../../ERP_OrderManage/ERP_ProjectOrder/components/dialog/selectprocureContract.vue";
import selectinvoice from "./dialog/selectinvoice.vue";
import selectCollection from "./dialog/selectCollection.vue";

import { useDetail } from "@/views/ERP_InvoiceManage/ERP_SupplierInvoice/components/utils/hooks";
import dayjs from "dayjs";
// 路由跳转
const { toDetail, router } = useDetail();
// 路由跳转
const route = useRoute();

const ruleFormRef = ref<FormInstance>();
onMounted(() => {
  if (state.value == "view" || state.value == "edit") {
    getinfo();
  }
});

const form = reactive({
  id: "",
  contractId: "",
  contractName: "",
  saleContractId: "",
  contractNo: "",
  signDate: "",
  projectName: "",
  contractMethod: "",
  contractTotalPrice: "",
  receiveDate: "",
  receivePrice: "",
  receiveType: "",
  receiveNodeId: [],
  receiveNodeName: "",
  fileVoList: "",
  mark: "",
  Files: [],
  processInstanceId: ""
});

// 付款方式
const getFKFS = (query?: string) => {
  getDict({
    key: "collectionMethods"
  }).then((response: any) => {
    OptionsFKFS.length = 0;
    for (const key in response.data) {
      OptionsFKFS.push({
        label: response.data[key],
        value: key
      });
    }
  });
  if (query) {
    setTimeout(() => {
      getDict;
    }, 1500);
  }
};
// 付款节点
const getFKJD = (query?: string) => {
  getcontractnodepaylist({
    pageIndex: 1,
    pageSize: 999,
    contractId: form.contractId
  }).then((response: any) => {
    for (const key in response.data.records) {
      OptionsFKJD.length = 0;
      OptionsFKJDlist.length = 0;
      OptionsFKJD.push({
        label:
          response.data.records[key].nodeTypeName +
          "-" +
          response.data.records[key].nodeMark,
        value: response.data.records[key].id
      });
      OptionsFKJDlist.push({
        label:
          response.data.records[key].nodeTypeName +
          "-" +
          response.data.records[key].nodeMark,
        value: response.data.records[key].id,
        backPayRate: response.data.records[key].backPayRate
      });
    }
  });
};

//字典
let OptionsFKFS = reactive([]);
let OptionsFKJD = reactive([]);
let OptionsFKJDlist = reactive([]);
//表格数据
const invoiceTableData = ref([]);
const CollectionTableData = ref([]);
const receiveTableData = ref([]);
const SKTableData = ref([
  { relatedReceiveDate: "", relatedReceiveType: "", relatedReceiveAmount: "" }
]);

//表单校验
const rulesForStepOne = reactive<FormRules>({
  receiveDate: [{ required: true, message: "请选择付款时间", trigger: "blur" }],
  receivePrice: [
    { required: true, message: "请输入付款金额", trigger: "blur" }
  ],
  receiveType: [{ required: true, message: "请选择付款方式", trigger: "blur" }],
  receiveNodeId: [
    { required: true, message: "请选择付款节点", trigger: "change" }
  ]
});

//数据显示隐藏
const isShow = ref(false);
const activeName = ref("A");

// 获取详情
const getinfo = async () => {
  const all = await getpaymentinfo({ id: route.query.id }).then(
    (response: any) => {
      form.id = response.data.id;
      form.contractId = response.data.contractId;
      form.contractName = response.data.contractName;
      form.contractNo = response.data.contractNo;
      form.signDate = response.data.signDate;
      form.projectName = response.data.projectName;
      form.contractMethod = response.data.contractMethod;
      form.contractTotalPrice = response.data.contractTotalPrice;
      form.receiveDate = response.data.receiveDate;
      form.receivePrice = response.data.receivePrice;
      form.receiveType = response.data.receiveType;
      form.receiveNodeId = response.data.receiveNodeId
        ? response.data.receiveNodeId.split(",")
        : [];
      form.fileVoList = response.data.fileVoList;
      form.mark = response.data.mark;
      form.processInstanceId = response.data.processInstanceId;
      SKTableData.value = [
        {
          relatedReceiveType: response.data.relatedReceiveType,
          relatedReceiveAmount: response.data.relatedReceiveAmount,
          relatedReceiveDate: response.data.relatedReceiveDate
        }
      ];
    }
  );
  let params: any = {};
  params.receiveId = form.id;
  paymentgetReceiveInvoice(params).then((response: any) => {
    if (response.data) {
      response.data.forEach(res => {
        //开票日期
        if (res.invoiceDate) {
          const date = new Date(res.invoiceDate);
          res.invoiceDate =
            date.getFullYear() +
            "-" +
            (date.getMonth() + 1) +
            "-" +
            date.getDate();
        }
        if (res.receiveStatus) {
          if (res.receiveStatus == "1") {
            res.receiveStatus = "未关联";
          } else if (res.receiveStatus == "2") {
            res.receiveStatus = "部分关联";
          } else if (res.receiveStatus == "3") {
            res.receiveStatus = "已关联";
          }
        }
        if (res.invoiceFile) {
          res.invoiceFile = JSON.parse(res.invoiceFile) || [];
        }
        if (res.settlementFile) {
          res.settlementFile = JSON.parse(res.settlementFile) || [];
        }
      });
      invoiceTableData.value = response.data;
    }
  });
  getpaymenthistory(params).then((response: any) => {
    if (response.data) {
      // response.data.forEach(res => {
      //   if (res.file) {
      //   }
      // });
      CollectionTableData.value = response.data.map(v => {
        return {
          ...v,
          file: (v.file && JSON.parse(v.file)) || []
        };
      });
    }
  });
  getExamineTableData();
  getFKFS();
  getpaymentnode({ id: route.query.id }).then((response: any) => {
    if (response.data) {
      receiveTableData.value = response.data;
      for (const key in response.data) {
        OptionsFKJD.push({
          label: response.data[key].nodeName,
          value: response.data[key].nodeId
        });
      }
    }
  });
};

//弹窗打开
let dialogVisiblesales = ref(false);
function showSalescontract() {
  if (state.value === "edit") return;
  dialogVisiblesales.value = true;
}
function closeSalescontract(val: any) {
  if (val == false) {
    dialogVisiblesales.value = false;
  } else {
    form.contractId = val.value.id;
    form.contractName = val.value.contractName;
    form.contractNo = val.value.contractNo;
    form.saleContractId = val.value.saleContractId;
    form.signDate = val.value.signDate;
    form.projectName = val.value.projectName;
    form.contractMethod = val.value.contractMethod;
    form.contractTotalPrice = val.value.contractTotalPrice;
    dialogVisiblesales.value = false;
    isShow.value = true;
    getFKFS();
    getFKJD();
    getpaymentinvoice({ contractId: form.contractId }).then((response: any) => {
      if (response.data) {
        response.data.forEach(res => {
          //开票日期
          if (res.invoiceDate) {
            const date = new Date(res.invoiceDate);
            res.invoiceDate =
              date.getFullYear() +
              "-" +
              (date.getMonth() + 1) +
              "-" +
              date.getDate();
          }
          if (res.receiveStatus) {
            if (res.receiveStatus == "1") {
              res.receiveStatus = "未关联";
            } else if (res.receiveStatus == "2") {
              res.receiveStatus = "部分关联";
            } else if (res.receiveStatus == "3") {
              res.receiveStatus = "已关联";
            }
          }
          if (res.invoiceFile) {
            res.invoiceFile = JSON.parse(res.invoiceFile) || [];
          }
          if (res.settlementFile) {
            res.settlementFile = JSON.parse(res.settlementFile) || [];
          }
        });
        invoiceTableData.value = response.data;
      }
    });
    getpaymenthistory({ contractId: form.contractId }).then((response: any) => {
      if (response.data) {
        // response.data.forEach(res => {
        //   if (res.file) {
        //   }
        // });
        CollectionTableData.value = response.data.map(v => {
          return {
            ...v,
            file: (v.file && JSON.parse(v.file)) || []
          };
        });
      }
    });
  }
}

function changeReceiveDate(value) {
  if (value && receiveTableData.value.length) {
    receiveTableData.value = receiveTableData.value.map(v => {
      return {
        ...v,
        receiveDate: form.receiveDate
      };
    });
  }
}
function delreceiveTableData(row, index) {
  receiveTableData.value.splice(index, 1);
  form.receiveNodeId = receiveTableData.value.map(v => v.nodeId);
}
function changeReceiveNodeId(valueList) {
  if (valueList.length) {
    const list = OptionsFKJDlist.filter(v => valueList.includes(v.value));
    receiveTableData.value = list.map(v => {
      return {
        nodeId: v.value,
        nodeName: v.label,
        backPaymentDate: dayjs().format("YYYY-MM-DD"),
        receiveDate: form.receiveDate || dayjs().format("YYYY-MM-DD"),
        receivePrice: (
          Number(form.contractTotalPrice) *
          (Number(v.backPayRate) / 100)
        )
          .toFixed(4)
          .toString(),
        receiveStatus: "0"
      };
    });
  } else {
    receiveTableData.value = [];
  }
}

let dialogVisibleinvoice = ref(false);
function showinvoice() {
  dialogVisibleinvoice.value = true;
}
function closeinvoice(val: any) {
  if (val == false) {
    dialogVisibleinvoice.value = false;
  } else {
  }
}

let dialogVisibleCollection = ref(false);
function showCollection() {
  dialogVisibleCollection.value = true;
}
function closeCollection(val: any) {
  if (val == false) {
    dialogVisibleCollection.value = false;
  } else {
    SKTableData.value = [];
    let sumAmount = 0;
    for (let i in val) {
      SKTableData.value.push({
        relatedReceiveType: val[i].receiveType,
        relatedReceiveAmount: val[i].receivePrice,
        relatedReceiveDate: val[i].receiveDate
      });
      sumAmount += Number(val[i].receivePrice);
    }
    if (SKTableData.value[0].relatedReceiveAmount != "") {
      if (form.receivePrice == "" ? 0 : Number(form.receivePrice) > sumAmount) {
        form.receivePrice = "";
        ElMessage.error("付款金额超出收款金额，请重新输入");
      }
    }
  }
}

//清空事件
function clear() {
  isShow.value = false;
}
// 页面状态
const state = ref(route.query.action);

//上传
const fileList = ref<UploadUserFile[]>([]);
const contractFileList: any = [];
const filePreviewDialogVisible = ref(false);
const fileUrl = ref("");

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile: UploadFile) => {
  if (uploadFile.response) {
    const response = uploadFile.response as unknown as any;
    window.open(response.data.url, "_blank");
  } else {
    window.open(uploadFile.url, "_blank");
  }
};

// 文件上传成功,传参赋值，格式修改
const handleSuccess = (fileList: any) => {
  contractFileList.push(fileList.data);
  const formatterObj = [];
  for (let i in contractFileList) {
    let tempvalue: any = {};
    tempvalue.fileUrl = contractFileList[i].url;
    tempvalue.fileSuffix =
      "." +
      contractFileList[i].name.substring(
        contractFileList[i].name.lastIndexOf(".") + 1
      );
    tempvalue.fileOriginName = contractFileList[i].name;
    formatterObj.push(tempvalue);
  }
  form.fileVoList = JSON.stringify(formatterObj);
};
// 非新增不许删除
const beforeRemove = (uploadFile, uploadFiles) => {
  if (state.value == "add") {
    ElMessage.error("当前状态文件不可删除");
    return false;
  }
};

//保存
const rules = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      saveORupdate();
    } else {
      console.log("error submit!", fields);
    }
  });
};

//保存/编辑事件
const saveORupdate = async () => {
  const SKTableDataInfo: any = SKTableData.value?.[0] || {};
  const params: ApiParams = {
    contractId: form.contractId,
    contractNo: form.contractNo,
    file: JSON.stringify(form.Files),
    mark: form.mark,
    receiveDate: form.receiveDate,
    receivePrice: form.receivePrice,
    receiveType: form.receiveType,
    receiveNodeId: form.receiveNodeId,
    relatedReceiveType: SKTableDataInfo.relatedReceiveType,
    relatedReceiveAmount: SKTableDataInfo.relatedReceiveAmount,
    relatedReceiveDate: SKTableDataInfo.relatedReceiveDate,
    receiveNodes: receiveTableData.value.map(v => {
      const { _X_ROW_KEY, ...val } = v;
      return {
        ...val
      };
    })
  };
  if (route.query.action == "edit") {
    params.id = route.query.id;
  }
  paymentSaveOrUpdate(params).then((response: ApiResponse) => {
    if (response.code == 200) {
      document.getElementById("closeTagButtonRef").click();
      ElMessage({
        message: "保存成功",
        type: "success"
      });
      history.back();
    }
  });
};
//付款金额点击后事件
function receivePricechange() {
  let sumAmount = 0;
  for (let i in SKTableData.value) {
    sumAmount += Number(SKTableData.value[i].relatedReceiveAmount);
  }
  if (SKTableData.value[0].relatedReceiveAmount != "") {
    if (form.receivePrice == "" ? 0 : Number(form.receivePrice) > sumAmount) {
      form.receivePrice = "";
      ElMessage.error("付款金额超出收款金额，请重新输入");
    }
  }
}

// 通用行合并函数（将相同多列数据合并为一行）
const mergeRowMethod: VxeTablePropTypes.SpanMethod = ({
  row,
  _rowIndex,
  column,
  columnIndex,
  visibleData
}) => {
  if (state.value == "add" || state.value == "edit") {
    const fields = [
      "invoiceDate",
      "invoicePrice",
      "invoiceNo",
      "invoiceCode",
      "receiveStatus",
      "invoiceFile",
      "settlementFile",
      "contractPrePrice",
      "orderPrePrice",
      "prePrice",
      "receivePrice",
      "noReceivePrice"
    ];
    const fields2 = ["paymentInvoicePrice", "paymentPrice", "noPaymentPrice"];
    const cellValue = row[column.field];
    if (cellValue && fields.includes(column.field)) {
      const prevRow = visibleData[_rowIndex - 1];
      let nextRow = visibleData[_rowIndex + 1];
      if (
        prevRow &&
        prevRow[column.field] === cellValue &&
        row.invoiceId === prevRow.invoiceId
      ) {
        return { rowspan: 0, colspan: 1 };
      }
      if (
        nextRow &&
        nextRow[column.field] === cellValue &&
        row.invoiceId === nextRow.invoiceId
      ) {
        let count = 1;
        while (
          nextRow &&
          nextRow[column.field] === cellValue &&
          (row.id === visibleData[_rowIndex + count]?.id ||
            row.invoiceId === visibleData[_rowIndex + count]?.invoiceId)
        ) {
          count++;
        }
        return { rowspan: count, colspan: 1 };
      }
    }
    if (cellValue && fields2.includes(column.field)) {
      const prevRow = visibleData[_rowIndex - 1];
      let nextRow = visibleData[_rowIndex + 1];
      if (
        prevRow &&
        prevRow[column.field] === cellValue &&
        row.id === prevRow.id
      ) {
        return { rowspan: 0, colspan: 1 };
      }
      if (
        nextRow &&
        nextRow[column.field] === cellValue &&
        row.id === nextRow.id
      ) {
        let count = 1;
        while (
          nextRow &&
          nextRow[column.field] === cellValue &&
          (row.id === visibleData[_rowIndex + count]?.id ||
            row.invoiceId === visibleData[_rowIndex + count]?.invoiceId)
        ) {
          count++;
        }
        return { rowspan: count, colspan: 1 };
      }
    }
  }
};
function updatereceivePrice() {
  let sum = 0;
  for (let i in receiveTableData.value) {
    sum += Number(receiveTableData.value[i].receivePrice);
  }
  form.receivePrice = sum.toString();
}
///////////////////// 审批记录 /////////////////////
let examineTableData = ref([]);
const examineTableColumns = reactive([
  {
    field: "actName",
    title: "流程节点",
    width: 100
  },
  {
    field: "auditDate",
    title: "审批时间",
    width: 100
  },
  {
    field: "auditUserName",
    title: "审批人",
    width: 100
  },
  {
    field: "auditResultMsg",
    title: "审批结果",
    width: 100
  },
  {
    field: "auditMessage",
    title: "审批意见",
    width: 100
  }
]);
// 获取审批记录
async function getExamineTableData() {
  let params: any = {};
  params.processInstanceId = form.processInstanceId;
  if (!params.processInstanceId) return;
  try {
    const response: any = await getAuditHistoryTaskList(params);
    if (response.code === 200) {
      examineTableData.value = response.data;
    }
  } catch (error) {
  } finally {
  }
}
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  align-items: center;
}
.header-span {
  display: flex;
  align-items: center;
}
.item {
  display: flex;
  align-items: center;
  margin-left: 20px;
  font-size: 12px;
}
.container {
  height: 20px;
  width: 80px;
  text-align: center;
  border: 1px solid #eee;
  line-height: 20px;
  font-size: 12px;
  margin-right: 6px;
  border-radius: 20px;
}
.examine {
  display: grid;
  place-items: center;
  img {
    height: 15vh;
  }
}
</style>
